<?php

namespace app\common\model\mycurrency;

use addons\mycurrency\library\Common;
use app\common\model\Area;
use app\common\model\Config;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use app\common\library\MerchantStaffAuth;

class Agent extends Model
{

    //use SoftDelete;

    // 表名
    protected $name = 'mycurrency_agent';

    // 追加属性
    protected $append = [
        'status_text',
        'level_text',
        'role_type_text',
    ];

    const STATUS_ZHENGCHENG = 1;//代理商状态 = 正常
    const STATUS_JINYONG = 2;//代理商状态 = 禁用

    const IS_IDENTITY_GEREN = 1;//身份 = 个人
    const IS_IDENTITY_QIYE = 2;//身份 = 企业

    const ROLE_TYPE_DAILI = 1;//角色 = 区域代理
    const ROLE_TYPE_YEWUYUAN = 2;//角色 = 业务员

    const LEVEL_SHENG = 1;//代理商层级:1=省代
    const LEVEL_SHI = 2;//代理商层级:2=市代
    const LEVEL_QUXIAN = 3;//代理商层级:3=区县代

    //生成代理商唯一编号
    public static function getNumger(){
        $number = date('YmdHis') . mt_rand(1000, 9999);
        $exists = self::where('number', $number)->value('id');
        if (!$exists) {
            return $number;
        }
        return self::getNumger();
    }

    /**
     * 添加代理及业务员
     * @param array $params 注册信息
     * @param array $admin 管理员账号信息
     * @param int $pid 上级信息
    */
    public static function agentAdd($params,$admin,$pid = 0){
        if($params['role_type'] == self::ROLE_TYPE_DAILI){//如果是区域代理
            if(!$params['level']){
                throw new Exception('等级不能为空');
                return false;
            }
            if(!$params['city']){
                throw new Exception('代理地区不能为空');
                return false;
            }
            if(self::where(['agency_region_id' => $params['agency_region_id'],'deletetime' => null])->find()){
                throw new Exception('当前地区已存在代理');
                return false;
            }
            $params['citystr'] = $params['city'];
            unset($params['city']);
        }elseif ($params['role_type'] == self::ROLE_TYPE_YEWUYUAN){//如果是业务员
            unset($params['level']);
            unset($params['city']);
        }

        if ($pid == 0){
            if($params['divideinto'] > 100){
                throw new Exception('分成比例不能大于100');
                return false;
            }
        }else{
            $p_agent = self::get($pid);
            if(!$p_agent){
                throw new Exception('上级不存在');
                return false;
            }
            if($params['divideinto'] > $p_agent['divideinto']){
                throw new Exception("分成比例不能高于{$p_agent['divideinto']}");
                return false;
            }
        }

        //代理商编号
        $params['number'] = self::getNumger();
        $params['pid'] = $pid;
        $params['createtime'] = time();
        $agent = self::create($params);
        if (!$agent){
            throw new Exception('添加失败');
            return false;
        }

        $identity = $params['role_type'] == self::ROLE_TYPE_DAILI ? MerchantStaff::IDENTITY_DAILI : MerchantStaff::IDENTITY_YEWU;//身份
        $agent_id = null;//代理商id
        $business_agent_id = null;//业务员id

        $avatar = Config::where(['name' => 'user_default_headportrait'])->value('value');

        if($params['role_type'] == self::ROLE_TYPE_DAILI){//如果是区域代理
            $agent_id = $agent->id;
        }else if ($params['role_type'] == self::ROLE_TYPE_YEWUYUAN){//如果是业务员
            $business_agent_id = $agent->id;
        }
        $ret = MerchantStaff::register($admin['username'],$admin['password'],'',$params['phone'],[
            'identity' => $identity,
            'agent_id' => $agent_id,
            'business_agent_id' => $business_agent_id,
            'group_id' => 1,
            'nickname' => $params['name'],
            'avatar' => $avatar,
            'status' => 'normal',
        ]);
        if (!$ret){
            throw new Exception('管理员账号添加失败');
            return false;
        }
        return true;

    }

    /**
     * 编辑代理商及业务员
     * @param array $params 注册信息
     * @param int $agent_id 被编辑信息id
    */
    public static function agentUpdate($params,$agent_id){
        $agent = self::get($agent_id);
        if(!$agent){
            throw new Exception('信息不存在');
            return false;
        }

        //分成比例设置合规性验证
        if($agent['pid'] != 0){//如果有上级
            $p_agent_divideinto = self::where(['id' => $agent['pid'],'deletetime' => null])->value('divideinto');
            if($params['divideinto'] > $p_agent_divideinto){
                throw new Exception("分成比例不能高于{$p_agent_divideinto}");
                return false;
            }
        }else{
            if($params['divideinto'] > 100){
                throw new Exception('分成比例不能大于100');
                return false;
            }
        }
        $x_agent_divideinto = self::where(['pid' => $agent['id'],'deletetime' => null])->order('divideinto desc')->value('divideinto');
        if($x_agent_divideinto){
            if($params['divideinto'] < $x_agent_divideinto){
                throw new Exception("分成比例不得小于{$x_agent_divideinto}");
                return false;
            }
        }
        $agent->name = $params['name'];
        $agent->fullname = $params['fullname'];
        $agent->phone = $params['phone'];
        $agent->divideinto = $params['divideinto'];
        $agent->status = $params['status'];
        $agent->save();
        return true;
    }

    //

//    public function getWechatCodeImageAttr($value){
//        if($value){
//            $baseUrl = Common::GetHost();
//            return $baseUrl . $value;
//        }
//        return null;
//    }
//
//    public function getAlipayCodeImageAttr($value){
//        if($value){
//            $baseUrl = Common::GetHost();
//            return $baseUrl . $value;
//        }
//        return null;
//    }

    public function getStatusTextAttr($value, $data)
    {
        $str = '';
        if ($data['status'] == self::STATUS_ZHENGCHENG){
            $str = "正常";
        }elseif ($data['status'] == self::STATUS_JINYONG){
            $str = "禁用";
        }
        return $str;
    }

    public function getLevelTextAttr($value, $data)
    {
        $str = '';
        if ($data['level'] == self::LEVEL_SHENG){
            $str = "省代";
        }elseif ($data['level'] == self::LEVEL_SHI){
            $str = "市代";
        }elseif ($data['level'] == self::LEVEL_QUXIAN){
            $str = "区县代";
        }
        return $str;
    }

    public function getRoleTypeTextAttr($value, $data)
    {
        $str = '';
        if ($data['role_type'] == self::ROLE_TYPE_DAILI){
            $str = "区域代理";
        }elseif ($data['role_type'] == self::ROLE_TYPE_YEWUYUAN){
            $str = "业务员";
        }
        return $str;
    }

    public function getCreateTimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }

    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 遍历获得所有下级id
     * @param int $pid 上级id
     * @param array $ids 所有下级ids
     */
    public static function getJuniorIds($pid,$ids = []){
        $x_ids = self::where(['pid' => $pid])->column('id');
        foreach($x_ids as $k => $v){
            $ids[] = $v;
            $ids = self::getJuniorIds($v,$ids);
        }
        return $ids;
    }
    /**
     * 遍历获得所有下级的门店id
     * @param int $pid 上级id
     * @param array $ids 所有下级ids
     */
    public static function getJuniorStoreIds($pid,$ids = []){
        $x_ids = self::where(['pid' => $pid])->column('id');
        foreach($x_ids as $k => $v){
            $ids[] = $v;
            $ids = self::getJuniorIds($v,$ids);
        }
        array_push($ids,$pid);
        $stores_ids = [];
        $stores = MerchantStore::where(['agent_id'=>['in',$ids]])->select();
        foreach($stores as $k => $v){
            $stores_ids[] = $v['id'];
        }
        return $stores_ids;
    }
}
